import { PhysicsSystem } from "../physics/physics";  
import { Enemy } from "./enemy";  
import { Vector2 } from "../vector";  
  
export class EnemyPhysics {  
  gravity = 0.25;  
  maxSpeed = 2.0;  
  isOnGround = false;  
    
  constructor(private physics: PhysicsSystem, private enemy: Enemy) {}  
  
  update_(): void {  
    if (this.enemy.isDead) return;  
  
    const body_ = this.enemy.body_;  
    body_.oldPos = body_.pos.copy();  

    // 地面检测 - 类似玩家的射线检测  
    const rayResult = this.physics.castRay(  
      new Vector2(body_.pos.x, body_.pos.y - 10),  
      new Vector2(body_.pos.x, body_.pos.y + 20)  
    );  
  
    if (rayResult) {  
      // 如果检测到地面，将敌人放置在地面上  
      body_.pos.y = rayResult.y - body_.radius;  
      body_.vel.y = 0;  
      this.isOnGround = true;  
    } else {  
      // 如果没有地面，应用重力  
      body_.vel.y += this.gravity;  
      this.isOnGround = false;  
    }  
  
    // 应用重力  
    body_.vel.y += this.gravity;  
      
    // 限制速度  
    body_.vel.x = Math.max(-this.maxSpeed, Math.min(this.maxSpeed, body_.vel.x));  
      
    // 应用摩擦力  
    body_.vel.x *= 0.9;  
      
    // 更新位置  
    body_.pos.add_(body_.vel);  
  
    // 碰撞检测  
    const collisions = Array.from(this.physics.checkHitterColisions(body_));  
      
    for (const collision of collisions) {  
      body_.contactPoints.push(collision.point);  
        
      if (collision.receiver_.isDeadly) {  
        this.enemy.die();  
        return;  
      }  
        
      // 简单的碰撞响应  
      body_.pos.sub_(collision.penetration);  
        
      // 如果碰到地面，停止下落  
      if (collision.penetration.y < 0) {  
        body_.vel.y = 0;  
      }  
    }  
  
    // 边界检查  
    if (body_.pos.y > this.enemy.engine.level_.size_.y) {  
      this.enemy.die();  
    }  
  }  
}